﻿using System.Windows.Controls;
using System.Windows.Input;
using System.Windows;
using Microsoft.Xaml.Behaviors;

namespace Super.Hmi.Behavior
{
    public class TreeViewItemBehavior : Behavior<TreeViewItem>
    {
        // 定义命令和命令参数依赖属性
        public static readonly DependencyProperty CommandProperty = DependencyProperty.Register("Command", typeof(ICommand), typeof(TreeViewItemBehavior));
        public static readonly DependencyProperty CommandParameterProperty = DependencyProperty.Register("CommandParameter", typeof(object), typeof(TreeViewItemBehavior));
        public ICommand Command
        {
            get { return (ICommand)GetValue(CommandProperty); }
            set { SetValue(CommandProperty, value); }
        }
        public object CommandParameter
        {
            get { return GetValue(CommandParameterProperty); }
            set { SetValue(CommandParameterProperty, value); }
        }
        protected override void OnAttached()
        {
            base.OnAttached();
            this.AssociatedObject.Selected += OnTreeViewItemSelected;
            this.AssociatedObject.MouseDoubleClick += OnTreeViewItemDoubleClick;
        }
        protected override void OnDetaching()
        {
            base.OnDetaching();
            this.AssociatedObject.Selected -= OnTreeViewItemSelected;
            this.AssociatedObject.MouseDoubleClick -= OnTreeViewItemDoubleClick;
        }
        private void OnTreeViewItemSelected(object sender, RoutedEventArgs e)
        {
            if (Command?.CanExecute(CommandParameter) == true)
            {
                Command.Execute(CommandParameter ?? AssociatedObject.DataContext);
            }
            e.Handled = true;
        }
        private void OnTreeViewItemDoubleClick(object sender, MouseButtonEventArgs e)
        {
            if (Command?.CanExecute(CommandParameter) == true)
            {
                Command.Execute(CommandParameter ?? AssociatedObject.DataContext);
            }
            e.Handled = true;
        }
    }
}
